import { ref, watch, nextTick } from 'vue'
import { defineStore } from 'pinia'

export const useThemeStore = defineStore('theme', () => {
    const theme = ref('light')
    const setTheme = (value: string) => {
        if (value === 'dark') {
            document.documentElement.classList.add('dark')
        } else {
            document.documentElement.classList.remove('dark')
        }
        theme.value = value
    }
    return { theme, setTheme }
}, {
    persist: {
        storage: {
            getItem(key) {
                return localStorage.getItem(key)
            },
            setItem(key, value) {
                localStorage.setItem(key, value)
            }
        }
    }
})

export const useSettingsStore = defineStore('settings', () => {
    // 状态：是否启用绿涨红跌（默认红涨绿跌）
    const greenRise = ref(true)

    // 更新根元素类名（同步CSS变量）
    const updateRootClass = async (val: boolean) => {
        await nextTick() // 确保DOM已挂载
        const htmlEl = document.documentElement
        if (val) {
            htmlEl.classList.add('rules-green-rise')
        } else {
            htmlEl.classList.remove('rules-green-rise')
        }
    }

    // 监听状态变化，自动同步类名
    watch(
        greenRise,
        (val) => {
            updateRootClass(val)
        },
    )

    // 1. 切换规则（红涨绿跌 ↔ 绿涨红跌）
    const toggleRiseFallRules = () => {
        greenRise.value = !greenRise.value
    }

    // 2. 外部传入设置规则（允许手动指定）
    // isGreenRise为true：绿涨红跌；false：红涨绿跌
    const setRiseFallRules = (isGreenRise: boolean) => {
        greenRise.value = isGreenRise
    }

    // 持久化到localStorage
    watch(
        greenRise,
        (val) => {
            localStorage.setItem('greenRise', JSON.stringify(val))
        },
    )

    // 初始化：从localStorage读取（刷新后恢复）
    const saved = localStorage.getItem('greenRise')
    if (saved !== null) {
        greenRise.value = JSON.parse(saved)
        updateRootClass(greenRise.value) // 手动同步类名（关键）
    }

    return {
        greenRise, // 当前规则状态
        toggleRiseFallRules, // 切换规则方法
        setRiseFallRules // 外部设置规则方法
    }
})